from PyQt5.QtWidgets import QFileDialog, QMessageBox
from qgis._core import QgsVectorLayer, QgsProject, QgsLineSymbol, QgsSingleSymbolRenderer, QgsVectorFileWriter

from demo.tool import RouteMapTool


class Route():
    def __init__(self,canvas):
        # 初始化航线图层
        self.canvas = canvas
        self.route_layer = None
        self.is_drawing = False

    def start_drawing(self):
        """开始绘制航线"""
        print("开始绘制航线模式")
        self.is_drawing = True

        # 创建临时航线图层
        self.route_layer = QgsVectorLayer("LineString?crs=EPSG:4326", "临时航线", "memory")
        QgsProject.instance().addMapLayer(self.route_layer, False)

        # 设置样式：红色虚线
        symbol = QgsLineSymbol.createSimple({
            'color': '255,0,0,200',  # 红色
            'width': '2',  # 2像素宽
            'style': 'dash'  # 虚线
        })
        self.route_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

        # 添加到图层树
        root = QgsProject.instance().layerTreeRoot()
        route_group = root.findGroup("航线")
        if not route_group:
            route_group = root.addGroup("航线")
        route_group.addLayer(self.route_layer)

        # 连接画布点击事件
        self.map_tool = RouteMapTool(self.canvas, self.route_layer, self)
        self.canvas.setMapTool(self.map_tool)

    def exit_drawing(self):
        if self.is_drawing:
            if hasattr(self, 'map_tool'):
                self.canvas.unsetMapTool(self.map_tool)

            self.is_drawing = False
            print("退出航线绘制模式")

    def save_route(self):
        """保存当前航线"""
        if not self.route_layer or self.route_layer.featureCount() == 0:
            print("没有可保存的航线")
            QMessageBox.warning(None, "保存失败", "当前没有可保存的航线")
            return

        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存航线", "", "GeoJSON 文件 (*.geojson);;所有文件 (*)"
        )

        if file_path:
            # 确保文件扩展名正确
            if not file_path.endswith('.geojson'):
                file_path += '.geojson'

            # 保存为GeoJSON
            error = QgsVectorFileWriter.writeAsVectorFormat(
                self.route_layer,
                file_path,
                "utf-8",
                self.route_layer.crs(),
                "GeoJSON"
            )

            if error[0] == QgsVectorFileWriter.NoError:
                print(f"航线已保存至: {file_path}")
                QMessageBox.information(self, "保存成功", f"航线已成功保存至:\n{file_path}")
            else:
                print(f"保存失败: {error[1]}")
                QMessageBox.critical(self, "保存失败", f"保存航线时出错:\n{error[1]}")

    def clear_route(self):
        """清除当前航线"""
        if self.route_layer:
            # 退出绘制模式
            self.exit_drawing()

            # 从图层树中移除
            root = QgsProject.instance().layerTreeRoot()
            route_group = root.findGroup("航线")
            if route_group:
                route_group.removeLayer(self.route_layer)

            # 从项目中移除图层
            QgsProject.instance().removeMapLayer(self.route_layer.id())
            self.route_layer = None

            print("航线已清除")
            QMessageBox.information(None, "清除航线", "当前航线已成功清除")